﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Chemistry.Tools
{
    /// <summary>
    /// 危化Http （用于流程、得分点等配置）
    /// </summary>
    public class HttpBaseChemistry
    {
        static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static HttpClient GetHttpBase()
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri(Global.SERVER_URL);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            String token = Global.Client == null ? "" : Global.Client.Signin.accessToken;
            client.DefaultRequestHeaders.Add("accessToken", token);
            return client;
        }

        public static async Task<T> GetAsync<T>(string url) where T : class
        {
            HttpResponseMessage response = await GetHttpBase().GetAsync(url);  // Blocking call（阻塞调用）! 
            try
            {
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsAsync<T>();
                    return data;
                }
                else
                {
                    log.Error(string.Format("异步Get请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);
            }
            return null;
           
        }

        public static async Task<T> PostAsJsonAsync<T>(string url, object entity) where T : class
        {
            HttpResponseMessage response = await GetHttpBase().PostAsJsonAsync(url, entity);
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {
                log.Error(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }
    }
}
